package com.google.code.bbdsm.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.*;

import blackboard.admin.data.datasource.DataSource;
import blackboard.admin.persist.datasource.DataSourceLoader;
import blackboard.admin.persist.datasource.DataSourcePersister;
import blackboard.admin.data.IAdminObject.*;
import blackboard.base.BbList;
import blackboard.data.ValidationException;
import blackboard.persist.PersistenceException;


public class DataSourceManagerImpl implements DataSourceManager {

	Log log = LogFactory.getLog(getClass());
	private DataSourceLoader dataSourceLoader;
	
	private DataSourcePersister dataSourcePersister;

	public List findAll() throws PersistenceException {
		log.debug("Loading all data sources");
		BbList dataSources = dataSourceLoader.loadAll();
		return dataSources;
	}

	public Map<String, BbList> getObjectCounts() throws PersistenceException {
		Map<String, BbList> allCounts = new HashMap<String, BbList>();
		
		Iterator dataSourceIterator = findAll().iterator();
		
		DataSource currentDataSource;
		
		// for each data source
		while(dataSourceIterator.hasNext()){
			// load it's counts
			currentDataSource = (DataSource)dataSourceIterator.next();
			BbList counts = dataSourceLoader.loadAllAdminObjectCounts(currentDataSource.getBatchUid(), RowStatus.DEFAULT );
			
			//save them in the map
			allCounts.put(currentDataSource.getBatchUid(), counts);
			
		}
		return allCounts;
	}
	
	public DataSourceLoader getDataSourceLoader() {
		return dataSourceLoader;
	}

	public void setDataSourceLoader(DataSourceLoader dataSourceLoader) {
		this.dataSourceLoader = dataSourceLoader;
	}

	public DataSourcePersister getDataSourcePersister() {
		return dataSourcePersister;
	}

	public void setDataSourcePersister(DataSourcePersister dataSourcePersister) {
		this.dataSourcePersister = dataSourcePersister;
	}

	
	public void create(com.google.code.bbdsm.domain.DataSource dataSource) throws PersistenceException, ValidationException {
		
		blackboard.admin.data.datasource.DataSource newDs = new blackboard.admin.data.datasource.DataSource();
		log.debug("Attempting to create data source: [" + dataSource.getBatchUid() + ": " + dataSource.getDescription() + "]");
		newDs.setBatchUid(dataSource.getBatchUid());
		newDs.setDescription(dataSource.getDescription());
		dataSourcePersister.create(newDs);
	}

}
